from PySide6.QtUiTools import QUiLoader
from PySide6.QtWidgets import QHeaderView, QAbstractItemView, QTableWidgetItem, QMessageBox

from entity import currentuser
from opsql import studentOp


class Sorder():
    def __init__(self):
        self.ui = QUiLoader().load('view/订单.ui')
        self.inittable()
        self.ui.payBtn.clicked.connect(self.pay)
        self.ui.searchBtn.clicked.connect(self.inittable)
        self.initcombo()

    def inittable(self):
        oid=self.ui.idIn.text()
        ispay=self.ui.ispay.currentData()
        sid = currentuser.current_userid
        result = studentOp.searchorder(sid,oid,ispay)
        row = 0
        if result:
            row = len(result)
        self.ui.tableWidget.setRowCount(row)
        self.ui.tableWidget.setColumnCount(6)
        self.ui.tableWidget.setHorizontalHeaderLabels(['订单id', '电脑id', '是否支付', '金额', '开始时间', '结束时间'])
        self.ui.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
        self.ui.tableWidget.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
        self.ui.tableWidget.verticalHeader().setVisible(False)
        self.ui.tableWidget.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)

        for i in range(row):
            for j in range(6):
                data = QTableWidgetItem(str(result[i][j]))
                self.ui.tableWidget.setItem(i, j, data)

    def pay(self):
        row=self.ui.tableWidget.currentRow()
        if row==-1:
            QMessageBox.warning(self.ui,'提示','请选择订单')
            return
        
        # 获取订单金额
        cost_text = self.ui.tableWidget.item(row,3).text()
        try:
            cost = int(cost_text)
        except ValueError:
            QMessageBox.warning(self.ui,'提示','订单金额格式错误')
            return
        
        # 检查学生余额
        sid = currentuser.current_userid
        student_info = studentOp.searchself(sid)
        if not student_info:
            QMessageBox.warning(self.ui,'提示','获取学生信息失败')
            return
        
        current_money = student_info[1]  # money字段
        
        if current_money < cost:
            QMessageBox.warning(self.ui,'提示',f'余额不足！当前余额：{current_money}元，订单金额：{cost}元')
            return
        
        oid=int(self.ui.tableWidget.item(row,0).text())
        if studentOp.pay(oid):
            QMessageBox.information(self.ui,'提示','支付成功')
            self.inittable()
        else:
            QMessageBox.warning(self.ui,'提示','支付失败')

    def initcombo(self):
        self.ui.ispay.addItem("请选择",-1)
        self.ui.ispay.addItem("未支付",0)
        self.ui.ispay.addItem("已支付",1)